<template>
  <div class="main">
    <!-- 公司查询 -->
    <el-card class="searchCard" shadow="never">
      <div slot="header" class="clearfix">
        <span>公司查询</span>
      </div>
      <el-form size="small" :inline="true" :model="searchForm" class="demo-form-inline">
        <div>
          <el-form-item class="searchIpt" label="登录账号:">
            <el-input v-model="searchForm.loginAccount" style="width:200px" size="mini" placeholder="请输入" />
          </el-form-item>
          <el-form-item class="searchIpt" label="公司名称:">
            <el-input v-model="searchForm.companyName" style="width:200px" size="mini" placeholder="请输入" />
          </el-form-item>
        </div>
        <div class="searchBtn">
          <el-form-item>
            <el-button plain @click="reset">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="doSearch">查询</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
    <!-- 公司后台账户管理-->
    <el-card class="staffList" shadow="never">
      <div slot="header" class="staffHeader">
        <span>公司后台账户管理</span>
        <el-button size="small" type="primary" @click="add()">添加商户</el-button>
        <el-dialog :title="title" :visible.sync="dialogFormVisible" top="15%" width="450px" @close="dialogClose">
          <el-form ref="form" :model="form" :rules="rules">
            <el-form-item label="登录账号" size="mini" prop="loginAccount" :label-width="formLabelWidth">
              <el-input v-model="form.loginAccount" placeholder="请输入开户手机号" style="width:250px" autocomplete="off" />
            </el-form-item>

            <el-form-item label="公司名称" prop="companyName" size="mini" :label-width="formLabelWidth">
              <el-input v-model="form.companyName" placeholder="请输入公司名称" style="width:250px" autocomplete="off" />
            </el-form-item>

            <el-form-item label="账户密码" size="mini" prop="password" :label-width="formLabelWidth">
              <el-input v-model="form.password" type="password" placeholder="请输入登录密码" style="width:250px" autocomplete="off" />
            </el-form-item>

            <el-form-item label="确认密码" size="mini" prop="checkPass" :label-width="formLabelWidth">
              <el-input v-model="form.checkPass" type="password" placeholder="请再次输入登录密码" style="width:250px" autocomplete="off" />
            </el-form-item>

            <el-form-item label="联系人姓名" prop="contactPerson" size="mini" :label-width="formLabelWidth">
              <el-input v-model="form.contactPerson" maxlength="20" placeholder="请输入联系人姓名" style="width:250px" autocomplete="off" />
            </el-form-item>
            <el-form-item>
              <div class="dialog-footer">
                <el-button size="small" @click="cancelAdd">取 消</el-button>
                <el-button size="small" type="primary" @click="submit">确 定</el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <!-- 新增内容表单 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{textAlign: 'center'}"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column
          prop="merchantId"
          label="商户编号"
          width="300"
        />
        <el-table-column
          prop="loginAccount"
          label="登录账号"
          width="300"
        />
        <el-table-column
          prop="companyName"
          label="公司名称"
          width="300"
        />
        <el-table-column
          prop="contactPerson"
          label="联系人姓名"
          width="300"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="300"
        >
          <!-- 操作按钮部分 -->
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleClick(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 显示表单信息 -->
      <el-dialog
        title="商户信息"
        :visible.sync="dialogVisible"
        width="40%"
        style="margin-top:220px;"
      >
        <div class="userMessage">
          <div>商户编号：{{ userMessage.merchantId }}</div>
          <div>商户账号：{{ userMessage.loginAccount }}</div>
          <div>公司名称：{{ userMessage.companyName }}</div>
          <div>联系人姓名：{{ userMessage.contactPerson }}</div>
        </div>
      </el-dialog>
      <!-- 关闭按钮 -->
      <div class="block">
        <el-pagination
          :current-page="page.currentPage"
          :page-sizes="page.pageSizes"
          :page-size="page.PageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
// 引入校验规则
import { isvalidPhone, isvalidPass } from '@/utils/validate'
import businessAccountApi from '@/api/businessAccount/index'

export default {
  components: {},
  data() {
    // 用户名
    var validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    // 密码
    var validatePass = function(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入密码 '))
      } else if (!isvalidPass(value)) {
        callback(
          new Error('8到20位数字、字母或符号组成,不可为纯数字')
        )
      } else {
        callback()
      }
    }
    // 确认密码
    var _this = this
    var validatePass2 = function(rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== _this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 这里存放数据
    return {
      //  名称
      title: '添加商户',
      // 分页设置
      page: {
        currentPage: 1, //  当前页
        pageSizes: [5, 10, 15, 20], // 预设每页显示个数
        pageSize: 5, // 每页显示个数
        total: 0 // 总条目数
      },
      // 判断是新增状态还是编辑状态
      isEditor: false,
      // 商户信息
      userMessage: {

      },
      // 表单验证
      rules: {
        loginAccount: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePass }
        ],
        checkPass: [
          { required: true, trigger: 'blur', validator: validatePass2 }
        ],
        companyName: [
          { required: true, message: '公司名称不能为空', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '联系人姓名不能为空', trigger: 'blur' },
          { max: 20, message: '最多不能超过20个字符', trigger: 'blur' }
        ]
      },
      // 查看表单内容显示
      dialogVisible: false,
      // 新增表单显示 是时候做出一些改变了
      dialogFormVisible: false,
      form: {
        merchantId: '', // id
        loginAccount: '', // 登录账号
        companyName: '', // 公司名称
        password: '', // 密码
        checkPass: '', // 确认密码
        contactPerson: ''// 联系人
      },
      formLabelWidth: '120px',
      searchForm: { // 搜索表单
        companyName: '', // 公司名称
        loginAccount: ''// 工资账号
      },
      // 员工列表数据
      tableData: []
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getBusinessAccountList()
    this.getPagenation()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    // 分页事件
    getPagenation() {
      businessAccountApi.findPage({
        pageSize: this.pagesizeVal,
        pageNum: this.pagenum
      }).then(res => {
        this.tableData = res.data.content
        this.page.total = res.data.totalSize
      })
    },
    // 获取商户数据列表
    getBusinessAccountList() {
      this.loading = true // 打开loading动画
      setTimeout(() => {
        businessAccountApi.getMerchantaccount().then(res => {
          var newArr = []
          for (var i = 0; i < 10; i++) {
            newArr.push(res.data[i])
          }
          if (res.code === 0) {
            // console.log(res.data)
            if (res.data.length !== 0) {
              this.pagenum = 1
              this.pagesizeVal = 10
              this.page.total = res.data.length
              this.tableData = newArr
            } else {
              this.tableData = []
            }
          } else {
            this.$message.error('获取列表失败')
          }
        })
        // businessAccountApi.findPage({
        //   pageNum: 1,
        //   pageSize: 10
        // }).then(res => {
        //   console.log(res)
        //   this.page.total = res.data.totalSize
        //   this.tableData = res.data.content
        // })
        this.loading = false// 关闭loading动画，
      })
    },

    // 点击新增按钮,新增内容
    add() {
      this.title = '添加商户'
      this.isEditor = false
      console.log(this.isEditor)
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['form'].resetFields()
      })
    },
    // 编辑表单内容
    edit(val) {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.title = '编辑商户'
      this.isEditor = true
      console.log(this.isEditor)
      this.dialogFormVisible = true
      this.form.loginAccount = val.loginAccount
      this.form.companyName = val.companyName
      this.form.password = ''
      this.form.checkPass = ''
      this.form.contactPerson = val.contactPerson
      this.form.merchantId = val.merchantId
    },
    // 搜索事件
    doSearch() {
      this.loading = true // 打开loading动画
      setTimeout(() => {
        businessAccountApi.searchList(
          this.searchForm
        ).then(res => {
          if (res.code === 0) {
            console.log(res)
            this.tableData = res.data
            this.page.total = res.data.length
          } else {
            this.$message.error('获取列表失败')
          }
        })
        this.loading = false// 关闭loading动画
      })
    },
    // 重置按钮方法
    reset() {
      this.page.currentPage = 1
      this.searchForm.loginAccount = ''
      this.searchForm.companyName = ''
      this.getBusinessAccountList()
    },

    // 查看表单内容按钮
    handleClick(row) {
      this.dialogVisible = true
      this.userMessage = row
      console.log(row)
    },

    // 每页多少条
    handleSizeChange(val) {
      this.pagesizeVal = val
      this.getPagenation()
    },
    // 改页数
    handleCurrentChange(val) {
      this.pagenum = val
      this.getPagenation()
    },

    // 关闭窗口清空添加表单
    resetForm() {
      this.$refs.form.resetFields()
    },
    dialogClose() {
      // this.resetForm()
    },
    // 点击确认按钮 清空并且关闭表单
    submit() {
      // 提交并且验证表单内容
      this.$refs.form.validate((valid) => {
        if (valid) {
          // alert('数据正确!')
          if (this.isEditor === false) {
            businessAccountApi.addBusiness(
              this.form
            ).then(res => {
              if (res.code === 0) {
                console.log(res)
                this.getBusinessAccountList()
              } else {
                this.$message.error('添加失败')
              }
            })
          }
          if (this.isEditor === true) {
            console.log('编辑中')
            businessAccountApi.updateById(this.form).then(res => {
              console.log(this.form)
              console.log(res)
              this.getBusinessAccountList()
            })
          }
          this.dialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 点击关闭按钮 清空并且关闭表单
    cancelAdd() {
      this.dialogFormVisible = false
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
  <style scoped lang="scss">
.main{
  width: 100%;
  height: 100%;
  background-color: #f0f2f5;
  overflow: hidden;
 .searchCard{
   margin:30px;
   .clearfix{
     line-height: 22px;
   }
   .demo-form-inline{
     display: flex;
     justify-content: space-between;
   }
 }
 .staffList{
   margin: 30px;
   .block{
     padding: 20px;
     display: flex;
     justify-content: center;
   }
 }
.staffHeader{
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .dialog-footer{
      display: flex;
      justify-content: end;
    }
}
.userMessage{
  padding: 0px 10px
}
.userMessage div{
  margin-bottom: 20px;
}
}
</style>
